package edu.iscas.appcheckclient.service.network;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.nio.charset.Charset;

import edu.iscas.appcheckclient.model.actions.Action;
import edu.iscas.appcheckclient.model.actions.Request;

/**
 * Created by dell on 2015/12/2.
 */
public class Uploader {
    private static RequestManager requestManager;
    private static Uploader uploader;

    private static String tagJson = "JSON REQUEST";
    private static String serverAddress = "";

    private Context context;

    private Uploader(Context ctx, String serverAddress){
        this.context = ctx;
        Uploader.serverAddress = serverAddress;
        requestManager = RequestManager.getInstance(ctx);
    }

    public static synchronized Uploader getInstance(Context ctx, String serverAddress){
        if(uploader == null){
            uploader = new Uploader(ctx, serverAddress);
        }
        return uploader;
    }

    public void uploadTest(String uploadAddress,final Request request, Response.Listener<String> listener, Response.ErrorListener errorListener){

        String url = serverAddress + uploadAddress;
        Toast.makeText(context,url,Toast.LENGTH_SHORT).show();

        for(Action action : request.getActionList()){
            action.setStatement(action.brewStatement(true));
        }

        for(Action action : request.getMockedHttpResponseList()){
            action.setStatement(action.brewStatement(true));
        }

        for(Action action : request.getMockedLocationList()){
            action.setStatement(action.brewStatement(true));
        }

        Log.d("uploadTest", request.toJSON());
        Log.d("content encoding", Charset.defaultCharset().displayName());
        Log.d("tangbo",request.toJSON().toString());
        StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener){
            @Override
            public byte[] getBody() throws AuthFailureError {
                return request.toJSON().getBytes(Charset.forName("UTF-8"));
            }

            @Override
            public String getBodyContentType() {
                return "application/json";
            }


//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                HashMap<String, String> headers = new HashMap<String, String>();
//                headers.put("Content-Type", "application/json");
//                return headers;
//            }
        };
        stringRequest.setTag(tagJson);
        requestManager.addToRequestQueue(stringRequest);
    }
}
